package com.lechi.web.controller;

import com.github.pagehelper.PageInfo;
import com.lechi.web.common.annotation.Anonymous;
import com.lechi.web.common.annotation.Log;
import com.lechi.web.common.constant.HttpStatus;
import com.lechi.web.common.core.controller.BaseController;
import com.lechi.web.common.core.domain.AjaxResult;
import com.lechi.web.common.enums.BusinessType;
import com.lechi.web.common.enums.ErrorCodeEnum;
import com.lechi.web.common.exception.ServiceException;
import com.lechi.web.common.utils.DateUtils;
import com.lechi.web.common.utils.file.FileUtils;
import com.lechi.web.service.IIotFtpUploadsService;
import com.lechi.web.system.domain.IotFtpUploads;
import com.lechi.web.vo.IotFtpUploadsVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 设备上传图片Controller
 *
 * @author yangguang
 * @date 2024 -06-03
 */
@RestController
@RequestMapping("/iot/ftp")
@RequiredArgsConstructor
public class IotFtpUploadsController extends BaseController {

    private final IIotFtpUploadsService iotFtpUploadsService;

    /**
     * 查询设备上传图片列表
     *
     * @param iotFtpUploadsVo the iot ftp uploads vo
     * @return the table data info
     */
    @Anonymous
    @GetMapping("/list")
    public AjaxResult list(IotFtpUploadsVo iotFtpUploadsVo) {
        IotFtpUploads iotFtpUploads = new IotFtpUploads();
        BeanUtils.copyProperties(iotFtpUploadsVo, iotFtpUploads);
        AjaxResult success = AjaxResult.success();
        success.put("code", HttpStatus.SUCCESS);
        success.put("rows", new int[0]);
        if (Objects.isNull(iotFtpUploadsVo.getParams().get("beginTime")) || Objects.isNull(iotFtpUploadsVo.getParams().get("endTime"))) {
            IotFtpUploads iotFtpUploads1 = iotFtpUploadsService.selectLastIotFtpUploads(iotFtpUploads);
            if (Objects.isNull(iotFtpUploads1)) {
                success.put("beginTime", DateUtils.getLastTime(new Date(), -5));
                success.put("endTime", new Date());
                return success;
            }
            iotFtpUploads.setParams(Map.of("beginTime", DateUtils.getLastTime(iotFtpUploads1.getCreateTime(), -5), "endTime", iotFtpUploads1.getCreateTime()));
            success.put("beginTime", DateUtils.getLastTime(iotFtpUploads1.getCreateTime(), -5));
            success.put("endTime", iotFtpUploads1.getCreateTime());
        } else {
            final Date beginTime = DateUtils.parseDate(iotFtpUploadsVo.getParams().get("beginTime"));
            final Date endTime = DateUtils.parseDate(iotFtpUploadsVo.getParams().get("endTime"));
            if (!beginTime.before(endTime)) {
                throw new ServiceException(ErrorCodeEnum.DATE_TIME_ERROR.getValue(), ErrorCodeEnum.DATE_TIME_ERROR.getKey());
            }
            iotFtpUploads.setParams(Map.of("beginTime", beginTime, "endTime", endTime));
        }

        startPage();
        List<IotFtpUploads> list = iotFtpUploadsService.selectIotFtpUploadsList(iotFtpUploads);
        success.put("rows", list);
        success.put("total", new PageInfo(list).getTotal());
        return success;
    }


    /**
     * 本地资源通用下载
     *
     * @param id       the id
     * @param response the response
     */
    @GetMapping("/download/{id}")
    public void resourceDownload(@PathVariable("id") Long id, HttpServletResponse response) {
        try {
            IotFtpUploads iotFtpUploads = new IotFtpUploads();
            iotFtpUploads.setId(id);
            List<IotFtpUploads> list = iotFtpUploadsService.selectIotFtpUploadsList(iotFtpUploads);
            IotFtpUploads iotFtp = list.get(0);
            String downloadPath = iotFtp.getFilepath();
            String downloadName = iotFtp.getFilename();
//            URL u = new URL("file:///" + downloadPath);
//            response.setContentType(u.openConnection().getContentType());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            response.setHeader("Content-disposition", "inline; filename=" + downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            throw new ServiceException(ErrorCodeEnum.DOWNLOAD_ERROR.getValue(), ErrorCodeEnum.DOWNLOAD_ERROR.getKey());
        }
    }


    /**
     * 获取设备上传图片详细信息
     *
     * @param id the id
     * @return the info
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        iotFtpUploadsService.selectIotFtpUploadsById(id);
        return AjaxResult.success();
    }

    /**
     * 新增设备上传图片
     *
     * @param iotFtpUploads the iot ftp uploads
     * @return the ajax result
     */
    @Log(title = "设备上传图片", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotFtpUploads iotFtpUploads) {
        iotFtpUploadsService.insertIotFtpUploads(iotFtpUploads);
        return AjaxResult.success();
    }


    /**
     * 删除设备上传图片
     *
     * @param ids the ids
     * @return the ajax result
     */
    @Log(title = "设备上传图片", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        iotFtpUploadsService.deleteIotFtpUploadsByIds(ids);
        return AjaxResult.success();
    }
}
